//
//  ZRNetworkTools.swift
//  XJ8XWB
//
//  Created by 中二 on 2016/10/25.
//  Copyright © 2016年 中二. All rights reserved.
//

import UIKit
import AFNetworking

enum ZRNetworkToolsMethod:String {
    case get = "get"
    case post = "post"
    
}

class ZRNetworkTools: AFHTTPSessionManager {
    static let sharedTools:ZRNetworkTools = {
        
        let tools = ZRNetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
        
        
    }()
    
    func requet(method:ZRNetworkToolsMethod,urlString:String,parameters:Any?,success:@escaping (Any?) -> (),failure:@escaping (Error)->()){
        
        if method == .get {
            
            get(urlString,parameters:parameters,progress:nil,success:{(_,responseObject) in
                
                success(responseObject)
                },failure:{(_,error) in
                    failure(error)
            
        })
        }else {
            // post 请求
            post(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) in
                success(responseObject)
                }, failure: { (_, error) in
                    failure(error)
            })
    
        }
    
}


}

extension ZRNetworkTools {
    
    func homeLoadData(success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        // 请求 url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        // 请求参数
        let params = ["access_token": ZRUserAccountViewModel.sharedTools.accessToken!]
        // 发送请求
        requet(method: ZRNetworkToolsMethod.get, urlString: urlString, parameters: params, success: success, failure: failure)
    }
    
}



extension ZRNetworkTools {
    
    //获取 userAccount
    
    func oauthLoadUserAccount(code:String,success:@escaping (Any?) -> (),failure:@escaping (Error) -> () ){
        
        // 请求 urlString
        let urlString = "https://api.weibo.com/oauth2/access_token"
        // 请求参数
        let params = [
        "client_id": HMAPPKEY,
        "client_secret": HMAPPSECRET,
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": HMREDIRECTURI
        ]
        //发送请求
        requet(method: ZRNetworkToolsMethod.post, urlString: urlString, parameters: params, success: success, failure: failure)
        
        
    }
    
    func oauthLoadUserInfo(model:ZRUserAccountModel,success:@escaping (Any?)->(), failure:@escaping (Error)->()){
        
        
        // 请求 urlString
        let urlString = "https://api.weibo.com/2/users/show.json"
        // 请求参数
        let params = [
            "access_token":model.access_token!,
            "uid":model.uid!
        ]
        // 发送请求
        requet(method: ZRNetworkToolsMethod.get, urlString: urlString, parameters: params, success: success, failure: failure)
        
    }
    
    
    
}






















